package com.catazy.module_compose.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.catazy.module_compose.bean.ArticleDetail
import com.catazy.module_compose.repository.ComposeRepository
import com.catazy.wanandroid.common_base.ext.Resource
import com.catazy.wanandroid.common_base.ext.logE
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.zip
import kotlinx.coroutines.launch

/**
 * 作者: Tao
 * 日期: 2024/5/7
 * 时间: 16:33
 * 描述: compose viewmodel
 */
class ComposeViewModel(private val repository: ComposeRepository) : ViewModel() {


    val articleLiveData = MutableLiveData<Resource<MutableList<ArticleDetail>>>()

    fun getArticles(pageNum: Int) {
        viewModelScope.launch {
            repository.getTopArticles()
                .zip(repository.getArticles(pageNum)) { topArticles, articles ->
                    {
                        val allArticles = mutableListOf<ArticleDetail>()
                        topArticles.data.forEach {
                            it.top = "1"
                        }
                        allArticles.addAll(topArticles.data)
                        allArticles.addAll(articles.data.datas)
                        allArticles
                    }
                }
                .catch {
                    logE(TAG, it.message, it)
                }
                .collectLatest {
                    articleLiveData.value = Resource.Success(it.invoke())
                }
        }
    }

    companion object {
        private const val TAG = "ComposeViewModel"
    }
}